<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="模版名称">
                <a-input allowClear placeholder="请输入模版名称" v-model="queryParam.name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="活动时间">
                <a-range-picker
                  format="YYYY-MM-DD HH:mm"
                  valueFormat="YYYY-MM-DD HH:mm"
                  :placeholder="['开始时间', '结束时间']"
                  v-model="queryTime"
                  @change="changeTime"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="getList()">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="getList()">
          <a-radio-button value="-1"> 全部 </a-radio-button>
          <a-radio-button value="1"> 未开始 </a-radio-button>
          <a-radio-button value="2"> 进行中 </a-radio-button>
          <a-radio-button value="3"> 已结束 </a-radio-button>
        </a-radio-group>

        <div>
          <a-button type="primary" icon="plus" @click="edit()">新建 </a-button>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="handleAll('change', '1')">批量启用</a-menu-item>
              <a-menu-item @click="handleAll('change', '0')">批量禁用</a-menu-item>
              <a-menu-item @click="handleAll('change', '2')">批量删除</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div>
      <a-table
        :rowKey="
          (r, i) => {
            return r.id
          }
        "
        :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
        size="default"
        :columns="columns"
        :data-source="list"
        :customRow="customRow"
        :scroll="{ x: 'max-content' }"
        :pagination="{
          total: this.total,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
      >
        <span slot="content" slot-scope="text, record">
          <div class="content">
            <div class="img">
              <a-avatar
                shape="square"
                :size="48"
                icon="user"
                :src="record.home_pic && record.home_pic.length ? record.home_pic[0] : ''"
              />
            </div>

            <div class="txt">
              <h3>{{ record.name }}</h3>
              <p>{{ record.cat_name }}</p>
            </div>
          </div>
        </span>

        <span slot="status" slot-scope="text, record">
          <a-badge :color="getStatus(record.status)[1]" :text="getStatus(record.status)[0]" />
        </span>

        <span slot="publish" slot-scope="text, record">
          <a-switch
            @change="handleItem('change', record, record.publish === '1' ? '0' : '1')"
            :checked="record.publish === '1'"
            checked-children="开"
            un-checked-children="关"
            default-checked
          />
        </span>

        <span slot="addtime" slot-scope="text, record">
          {{ record.addtime > 0 ? $moment(record.addtime * 1000).format('YYYY-MM-DD HH:mm:ss') : '-' }}
        </span>

        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="edit(record)">编辑</a-button>
          <a-divider type="vertical" />
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href="javascript:;" @click="handleItem('change', record, 2)">删除</a>
              </a-menu-item>
            </a-menu>
            <a class="ant-dropdown-link"> 更多 <a-icon type="down" /> </a>
          </a-dropdown>
        </span>
      </a-table>

      <!-- <a-modal width="700px" v-model="visible" title="新建模版" ok-text="确认" cancel-text="取消" @ok="onSubmit">
        <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-model-item label="活动名称" prop="name">
            <a-input v-model="form.name" allowClear />
          </a-form-model-item>
          <a-form-model-item label="活动时间" prop="queryTime">
            <a-range-picker
              style="width: 100%"
              format="YYYY-MM-DD HH:mm"
              valueFormat="YYYY-MM-DD HH:mm"
              :placeholder="['开始时间', '结束时间']"
              v-model="form.queryTime"
            />
          </a-form-model-item>
          <a-form-model-item label="活动商品" prop="goods_ids">
            <div class="flex">
              <a-input :value="goodsName" disabled placeholder="请选择活动商品" />
              <a-button style="margin-left: 10px" type="primary" @click="openGoods"> 添加商品 </a-button>
            </div>
          </a-form-model-item>
          <a-form-model-item label="活动优惠券" prop="coupon_ids">
            <a-select mode="multiple" placeholder="选择优惠券" v-model="form.coupon_ids">
              <a-select-option v-for="(item, index) in couonList" :value="item.id" :key="index">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
      </a-modal> -->
    </a-card>

    <popGoods @onOk="selectGoods" ref="popGoods"></popGoods>
  </page-header-wrapper>
</template>

<script>
import { List, Save, Status, Info, getCoupons } from '@/api/marketing/activityNew'
import popGoods from '../seckill/components/goods'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '活动名称',
    dataIndex: 'name',
    ellipsis: true,
    width: 200,
  },
  {
    title: '开始时间',
    dataIndex: 'start_time',
    width: 140,
  },
  {
    title: '结束时间',
    dataIndex: 'end_time',
    width: 140,
  },
  {
    title: '状态',
    scopedSlots: {
      customRender: 'status',
    },
  },
  {
    title: '上下架',
    scopedSlots: {
      customRender: 'publish',
    },
  },
  {
    title: '发布时间',
    dataIndex: 'created_at',
    sorter: (a, b) => a.created_at - b.created_at,
    width: 140,
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action',
    },
  },
]

export default {
  components: {
    popGoods,
  },
  data() {
    return {
      total: 0,
      pageNo: 1,
      pageSize: 10,
      columns,
      queryParam: {
        name: '',
        status: '-1',
      },
      list: [],
      selectedRowKeys: [],
      categoryInfo: [],
      visible: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      form: {
        name: '',
        queryTime: [],
        goods_ids: [],
        coupon_ids: [],
      },
      rules: {
        name: [{ required: true, message: '活动名称不能为空', trigger: 'blur' }],
        queryTime: [{ required: true, message: '活动时间不能为空', trigger: 'change' }],
        goods_ids: [{ required: true, message: '活动商品不能为空', trigger: 'change' }],
        coupon_ids: [{ required: true, message: '优惠券不能为空', trigger: 'change' }],
      },

      queryTime: [],
      goodsName: '',
      couonList: [],
    }
  },

  mounted() {
    this.getList()

    getCoupons().then((res) => {
      if (!res.code) {
        this.couonList = res.data || []
      }
    })
  },

  watch: {
    visible(e) {
      if (!e) {
        this.resetForm()
        this.goodsName = ''
      }
    },
  },

  computed: {
    getCatName() {
      return (id) => {
        let item = this.categoryInfo.find((el) => el.id === id)
        return item ? item.name : ''
      }
    },

    getStatus() {
      return (status) => {
        let text, color
        switch (String(status)) {
          case '1':
            text = '未开始'
            color = '#ff0000'
            break

          case '2':
            text = '进行中'
            color = '#65C817'
            break

          case '3':
            text = '已结束'
            color = '#918383'
            break
        }
        return [text, color]
      }
    },

    isShow() {
      return (is_show) => {
        let item = this.statusList.find((el) => el.id === is_show)
        return item
      }
    },
  },

  methods: {
    selectGoods(list) {
      this.form.goods_ids = list
      this.goodsName = list.map((el) => el.name).join(',')
    },

    openGoods() {
      this.$nextTick(() => {
        this.$refs.popGoods.visible = true
      })
    },

    async edit(item) {
      let id = 0
      if (item) {
        id = item.id
      }

      console.log('id,', id)
      this.$router.push(`/newActivity/Edit?id=${id}`)
      // this.visible = true
      // const hide = this.$message.loading('加载中', 0)

      // let res = await Info({ id })
      // if (!res.code) {
      //   let { activity, activity_goods: goods_ids } = res.data,
      //     { start_time, end_time, name, coupon_ids, id } = activity

      //   this.goodsName = goods_ids.map((el) => el.name).join(',')

      //   this.form = {
      //     id,
      //     name,
      //     queryTime: [start_time, end_time],
      //     goods_ids,
      //     coupon_ids: coupon_ids ? coupon_ids.split(',') : [],
      //   }

      //   console.log('res,',res.data)
      // }
      // hide()
    },
    // 切换筛选时间
    changeTime(e) {
      if (e.length) {
        this.queryParam.start_time = e[0]
        this.queryParam.end_time = e[1]
      } else {
        this.queryParam.start_time = ''
        this.queryParam.end_time = ''
      }
    },

    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          const hide = this.$message.loading('加载中', 0)
          let form = JSON.parse(JSON.stringify(this.form)),
            [start_time, end_time] = form.queryTime

          form.start_time = start_time
          form.end_time = end_time

          form.goods_ids = form.goods_ids.map((el) => el.id).join(',')
          form.coupon_ids = form.coupon_ids.join(',')
          delete form.queryTime
          const res = await Save(form)
          hide()
          if (res.code == 0) {
            this.$message.success('创建成功')
            this.visible = false
            this.getList()

            this.form = {
              name: '',
              queryTime: [],
              goods_ids: [],
              coupon_ids: [],
            }
            this.goodsName = ''
            return
          }
          this.$message.error(res.msg)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },

    // 获取数据列表
    async getList(pageNo = 1) {
      const hide = this.$message.loading('加载中', 0)
      let { queryParam, pageSize } = this
      const res = await List({
        ...queryParam,
        pageSize,
        pageNo,
      })
      console.log('res,', res)
      if (res.code == 0) {
        this.selectedRowKeys = []
        let { totalCount, data } = res.data
        this.total = totalCount
        this.list = data
      }
      hide()
    },

    // 分页请求
    tablePageChange(e) {
      this.getList(e)
    },

    // 选中多行
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    // 批量操作
    handleAll(type, status) {
      let { selectedRowKeys } = this
      if (!selectedRowKeys.length) {
        this.$message.error('请至少选择一条数据~')
        return
      }

      let ids = selectedRowKeys.join(',')

      switch (type) {
        case 'change':
          this.changeStatus(ids, status)
          break
      }
    },

    // 点击单个
    handleItem(type, item, status) {
      switch (type) {
        case 'change':
          this.changeStatus(item.id, status)
          break
      }
    },

    // 修改状态
    changeStatus(ids, status) {
      Status({
        ids,
        status,
      }).then((res) => {
        if (res.code) {
          this.$error({
            content: res.msg,
          })
        } else {
          this.$message.success(res.msg)
          this.getList()
          this.selectedRowKeys = []
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 8px 0 18px 0;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-right: 20px;
  }
  .select {
    display: flex;
    align-items: center;
    margin-right: 20px;
  }
}

.content {
  display: flex;
  align-items: center;
  height: 48px;
  max-width: 300px;
  overflow: hidden;

  .txt {
    margin-left: 16px;
    flex: 1;
    overflow: hidden;

    * {
      margin: 0;
      font-size: 14px;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }

    h3 {
      color: rgba(0, 0, 0, 0.85);
    }

    p {
      color: rgba(0, 0, 0, 0.45);
    }
  }
}

::v-deep {
  .ant-tag {
    cursor: pointer;
  }
}
</style>
